<?php

namespace app\admin\controller;

use app\common\business\SOrder as SOrderBus;
use app\common\lib\Check;
use app\common\lib\toCamelCase;
use app\common\model\mysql\SGoodsGroupBuying;
use app\common\model\mysql\SGoodsGroupUser;
use app\common\model\mysql\SMember;
use app\common\model\mysql\SOrderConfigure;
use app\common\model\mysql\SOrderGoods;
use app\common\model\mysql\SOrderRecord;
use app\common\model\mysql\SOrderRefundGoods;
use think\facade\Db;

class SOrder extends AuthBase
{
    //获取订单数据列表查询条件
    public function orderListSearch(){
        $where = [];
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $orderGoodsNames = $this->request->param('orderGoodsNames',"");
        $orderSn = $this->request->param('orderSn',"");
        $uid = $this->request->param('uid',"");
        $realName = $this->request->param('realName',"");
        $userPhone = $this->request->param('userPhone',"");
        $activityType = $this->request->param('activityType',"");
        $payType = $this->request->param('payType',"");
        $createTime = $this->request->param('createTime',"");
        if($orderGoodsNames){
            $where[] = ['order_goods_names', 'like', '%'.$orderGoodsNames.'%'];
        }
        if($orderSn){
            $where[] = ['order_sn', 'like', '%'.$orderSn.'%'];
        }
        if($uid){
            $where[] = ['uid', '=', $uid];
        }
        if($realName){
            $where[] = ['real_name', 'like', '%'.$realName.'%'];
        }
        if($userPhone){
            $where[] = ['user_phone', 'like', '%'.$userPhone.'%'];
        }
        if($activityType){
            $where[] = ['activity_type', '=', $activityType];
        }
        if($payType){
            if($payType == 1){
                $where[] = ['pay_type', 'in', [1,2,3]];
            }elseif($payType == 2){
                $where[] = ['pay_type', 'in', [4]];
            }elseif($payType == 3){
                $where[] = ['pay_type', 'in', [0]];
            }elseif($payType == 4){
                $where[] = ['pay_type', 'in', [5,6]];
            }
        }
        if($createTime){
            $where[] = ['create_time',">=",$createTime[0]." 00:00:00"];
            $where[] = ['create_time',"<=",$createTime[1]." 23:59:59"];
        }
        $where[] = ['del_flag', '=', '0'];
        return [
            'page'=>$page,
            'limit'=>$limit,
            'where'=>$where,
        ];
    }

    //订单列表
    public function orderList() {
        try {
            // 获取搜索条件和分页信息
            $searchData = $this->orderListSearch();
            // 获取订单数据
            $orderData = $this->getNormalOrderData($searchData);
            // 转换数据格式
            $orderData = $this->formatOrderData($orderData);
            // 处理订单商品数据
            $orderData = $this->addOrderGoodsData($orderData);
            // 返回成功响应
            return show(config("status.success"), "订单数据列表", $orderData);
        } catch (\Exception $e) {
            // 返回空数据
            return show(config("status.error"), $e->getMessage(), []);
            //return show(config("status.error"), "获取订单列表失败", []);
        }
    }

    // 获取正常订单数据
    private function getNormalOrderData($searchData) {
        return (new SOrderBus())->getNormalOrderData(
            $searchData['where'],
            '*',
            $searchData['limit'],
            $searchData['page']
        );
    }

    // 格式化订单数据
    private function formatOrderData($orderData) {
        if (isset($orderData['data'])) {
            return (new toCamelCase())->toCamelCaseArray($orderData);
        }
        return $orderData;
    }

    // 添加订单商品数据
    private function addOrderGoodsData($orderData) {
        if (isset($orderData['data']) && !empty($orderData['data'])) {
            foreach ($orderData['data'] as &$order) {
                $memberWhere = [
                    "member_id"=>$order['uid'],
                ];
                $MemberData = (new SMember())->getMemberIdData($memberWhere,"wechat_nickname");
                // 检查$MemberData是否为null
                if ($MemberData && isset($MemberData['wechat_nickname'])) {
                    $wechatNickname = $MemberData['wechat_nickname'];
                } else {
                    // 处理$MemberData为null或没有'wechat_nickname'索引的情况
                    $wechatNickname = null; // 或者设置为其他适当的默认值
                    // 可能还需要记录日志或执行其他错误处理逻辑
                }
                $orderGoodsData = (new SOrderGoods())->getOrderGoods($order['orderId']);
                // 初始化refundStatus为0，假设没有退款
                $refundStatus = 0;
                $activityStatus = '1';
                //状态：0。默认，进行中，1.已完成，2 时间到未完成
                // 遍历订单中的所有商品，检查是否有任何商品被退款
                foreach ($orderGoodsData as $goods) {
                    if ($goods['is_refund'] == 1) {
                        $refundStatus = 1; // 如果发现任何被退款的商品，将refundStatus设置为1
                        break; // 不需要继续检查其他商品，因为已经确定有退款
                    }
                    if ($goods['goods_type'] == 3) {
                        $activityData = (new SGoodsGroupBuying())->getGoodsGroupBuyingStatus($goods['activity_id']);
                        $activityStatus = $activityData ? $activityData['status'] : '1';
                    }
                }

                // 将refundStatus添加到订单数据中
                $order['refundStatus'] = $refundStatus;
                $order['activityStatus'] = $activityStatus;
                $order['orderGoodsData'] = $this->formatOrderGoodsData($orderGoodsData);
                $order['wechatNickname'] = $wechatNickname;
            }
        }
        return $orderData;
    }




    // 格式化订单商品数据
    private function formatOrderGoodsData($orderGoodsData) {
        foreach ($orderGoodsData as &$goods) {
            $goods['cart_info'] = json_decode($goods['cart_info'], true);
        }
        return $orderGoodsData;
    }

    //核销订单
    public function sellOrder(){
        $verifyCode = $this->request->param("verifyCode","","trim");
        if(empty($verifyCode)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $orderDB = (new SOrderBus());
            $checkOrder = $orderDB->checkOrderVerifyCode($verifyCode);
            if(empty($checkOrder)){
                return show(config('status.error'),"订单不存在");
            }else{
                if($checkOrder['activity_type'] == 2){
                    $checkGroupOrder = (new SGoodsGroupUser())->getGroupUserStatus($checkOrder['order_id'],'a.*,b.status as activityStatus');
                    if($checkGroupOrder['activityStatus'] === '0'){
                        return show(config('status.error'),'拼团订单暂未成功无法核销');
                    }elseif($checkGroupOrder['activityStatus'] === '2'){
                        return show(config('status.error'),'拼团订单未完成无法核销');
                    }elseif($checkGroupOrder['activityStatus'] === '1'){
                        $checkRefundOrder = (new SOrderGoods())->getOrderGoodsStatus($checkOrder['order_id']);
                        if($checkRefundOrder){
                            return show(config('status.error'),'订单有售后申请请先处理');
                        }
                    }
                }
            }
            $result = $orderDB->sellOrder($verifyCode,$checkOrder['order_id'],$this->userId);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"删除成功",$result);
    }

    //修改订单
    public function saveOrder(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        //参数校验
        $allParams = request()->param();
        $data = (new toCamelCase())->toCamelCaseArray($allParams,'1',2);
        try {
            $result = (new SOrderBus())->updateById($data['order_id'],$data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"修改订单",$result);
    }

    //删除订单
    public function orderDel(){
        $order = $this->request->param("order","","trim");
        if(empty($order)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $result = (new SOrderBus())->delOrderIds($order);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"删除成功",$result);
    }

    //立即付款订单
    public function PayOrder(){
        $order = $this->request->param("order","","trim");
        if(empty($order)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $result = (new SOrderBus())->payOrderIds($order);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"操作成功",$result);
    }

    // 提取构建退款数据的公共方法
    private function buildRefundData($params)
    {
        $orderConfigureData = (new SOrderConfigure())->getOrderConfigure($params['merId'],'consignee_name,consignee_phone,consignee_address');
        return [
            'order_refund_sn' => (new Check())->makeOrderNo(),
            'order_id' => $params['orderId'],
            'uid' => $params['uid'],
            'mer_id' => $params['merId'],
            'extension_one' => $params['extensionOne'],
            'extension_two' => $params['extensionTwo'],
            'mer_delivery_user' => $orderConfigureData['consignee_name'],
            'mer_delivery_address' => $orderConfigureData['consignee_address'],
            'phone' => $orderConfigureData['consignee_phone'],
            'mark' => '后台主动退款',
            'refund_message' => '后台主动退款',
            'refund_price' => $params['payPrice'],
            'refund_num' => $params['totalNum'],
            'status' => 3,
            'status_time' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s'),
            'admin_id' => $this->userId,
            'platform_commission' => $params['platformCommission'],
            'initiator_commission' => $params['initiatorCommission'],
            'sharer_commission' => $params['sharerCommission'],
            'partner_commission' => $params['partnerCommission'],
        ];
    }

    // 提取构建退款商品数据的公共方法
    private function buildRefundGoodsData($goodsData, $refundResId)
    {
        $refundGoodsData = [];
        foreach ($goodsData as $k => $v) {
            $refundGoodsData[$k] = [
                'order_refund_id' => $refundResId,
                'order_goods_id' => $v['order_goods_id'],
                'refund_price' => $v['total_price'],
                'refund_num' => $v['goods_num'],
                'create_time' => date('Y-m-d H:i:s'),
            ];
        }
        return $refundGoodsData;
    }

    // 提取构建更新退款数据的公共方法
    private function buildUpdateRefundData($params)
    {
        return [
            'refund_price' => $params['payPrice'],
            'status' => 3,
            'status_time' => date('Y-m-d H:i:s'),
            'admin_id' => $this->userId,
        ];
    }

    //立即退款订单
    public function refundOrder(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        $allParams = request()->param();

        Db::startTrans(); // 开始事务
        try {
            if ($allParams['orderRefundId'] === 0) {
                $refundData = $this->buildRefundData($allParams);
                $refundResId = (new SOrderBus())->addRefundOrder($refundData);

                if ($refundResId) {
                    $refundGoodsData = $this->buildRefundGoodsData($allParams['orderGoodsData'], $refundResId);
                    (new SOrderRefundGoods())->insertAllOrderRefundGoods($refundGoodsData);
                } else {
                    Db::rollback();
                    return show(config('status.error'),'添加退款订单失败');
                }
            } else {
                $saveRefundData = $this->buildUpdateRefundData($allParams);
                (new SOrderBus())->updateRefundById($allParams['orderRefundId'], $saveRefundData);
            }
            $result = (new SOrderBus())->refundOrderIds($allParams['orderId']);
            if ($result) {
                $saveOrderGoodsData = ['is_refund' => 3];
                (new SOrderGoods())->saveOrderGoodsId($allParams['orderId'], $saveOrderGoodsData);
            } else {
                Db::rollback();
                return show(config('status.error'),'退款订单ID失败');
            }
            Db::commit(); // 提交事务
            return show(config("status.success"), "操作成功", $result);
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
    }

    //订单已收货
    public function receiveOrder(){
        $order = $this->request->param("order","","trim");
        if(empty($order)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $result = (new SOrderBus())->receiveOrderIds($order);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"操作成功",$result);
    }

    //订单详情
    public function orderDetails(){
        $order = $this->request->param("order","","trim");
        if(empty($order)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $roleData = (new SOrderBus())->getOrderById($order);
            $roleData['orderIcon'] = (new Check())->getOrderIcon();
            $roleData['orderGoodsData'] = (new SOrderGoods())->getOrderGoods($roleData['order_id'],'goods_num,total_price,image,title');
            $memberWhere[] = ['member_id','=',$roleData['uid']];
            $roleData['memberData'] = (new SMember())->getMemberIdData($memberWhere);
            $where[] = ['order_id','=',$order];
            $roleData['logData'] = (new SOrderRecord())->getOrderRecordList($where);
            $roleData = (new toCamelCase())->toCamelCaseArray($roleData);
        }catch (\Exception $e){
            $roleData = [];
        }
        return show(config("status.success"),"订单详情",$roleData);
    }

    //订单添加
    public function orderAdd(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        //参数校验
        $allParams = request()->param();
        $data = (new toCamelCase())->toCamelCaseArray($allParams,'1',2);
        $data['goodsData'] = array(
            array(
                'goods_id'=>9,
                'num'=>1,
                'goods_type'=>1,
                'activity_id'=>0,
            ),array(
                'goods_id'=>10,
                'num'=>1,
                'goods_type'=>1,
                'activity_id'=>0,
            ),
        );
        // 初始化事务
        Db::startTrans();
        try {
            $result = (new SOrderBus())->addOrder($data);
            if($result){
                $orderGoodsData = $goodsNames = [];
                $SGoodsBus = (new \app\common\business\SGoods());
                foreach ($data['goodsData'] as $k=>$v){
                    $goodsData = $SGoodsBus->getGoodsById($v['goods_id']);
                    $orderGoodsData[$k]['order_id'] = $result;
                    $orderGoodsData[$k]['uid'] = 1;
                    $orderGoodsData[$k]['goods_id'] = $v['goods_id'];
                    $orderGoodsData[$k]['platform_commission'] = "0.01";
                    $orderGoodsData[$k]['initiator_commission'] = "0.02";
                    $orderGoodsData[$k]['sharer_commission'] = "0.03";
                    $orderGoodsData[$k]['partner_commission'] = "0.04";
                    $orderGoodsData[$k]['goods_num'] = $v['num'];
                    $orderGoodsData[$k]['goods_type'] = $v['goods_type'];
                    $orderGoodsData[$k]['activity_id'] = $v['activity_id'];
                    $orderGoodsData[$k]['refund_num'] = $v['num'];
                    $orderGoodsData[$k]['total_price'] = $goodsData['selling_price'];
                    $orderGoodsData[$k]['cart_info'] = json_encode($goodsData);
                    $orderGoodsData[$k]['create_time'] = date("Y-m-d H:i:s",time());
                    $orderGoodsData[$k]['title'] = $goodsData['goods_name'];
                    $orderGoodsData[$k]['image'] = $goodsData['main_img_url'];
                    $goodsNames[] = $goodsData['goods_name'];
                }
                $saveOrder['order_goods_names'] = implode(',', $goodsNames);
                (new SOrderGoods())->insertAllOrderGoods($orderGoodsData);
                (new SOrderBus())->updateById($result,$saveOrder);
            }
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        Db::commit();
        return show(config("status.success"),"新增成功",$result);
    }


    /*************************售后订单管理模块*******************************/

    //获取售后订单数据列表查询条件
    public function orderRefundListSearch(){
        $where = [];
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $orderRefundSn = $this->request->param('orderRefundSn',"");
        $status = $this->request->param('status',"");
        $createTime = $this->request->param('createTime',"");
        if($orderRefundSn){
            $where[] = ['a.order_refund_sn', 'like', '%'.$orderRefundSn.'%'];
        }
        if ($status !== null && $status !== '') {
            // 如果$status不为null且不为空字符串，则添加条件到$where数组
            $where[] = ["a.status", "=", $status];
        }
        if($createTime){
            $where[] = ['a.create_time',">=",$createTime[0]." 00:00:00"];
            $where[] = ['a.create_time',"<=",$createTime[1]." 23:59:59"];
        }
        $where[] = ['a.del_flag', '=', '0'];
        return [
            'page'=>$page,
            'limit'=>$limit,
            'where'=>$where,
        ];
    }

    //售后订单数据列表
    public function orderRefundList(){
        $searchData = $this->orderRefundListSearch();
        try {
            $field = "a.*,b.order_sn,b.pay_price,b.status as orderStatus,b.real_name";
            $orderRefundData = (new SOrderBus())->getNormalOrderRefundData($searchData['where'],$field,$searchData['limit'],$searchData['page']);
            $orderRefundData = $this->orderRefundGoodsData($orderRefundData);
            $orderRefundData = (new toCamelCase())->toCamelCaseArray($orderRefundData);
        }catch (\Exception $e){
            $orderRefundData = [];
        }
        return show(config("status.success"),"售后订单数据列表",$orderRefundData);
    }

    // 添加售后订单商品数据
    private function orderRefundGoodsData($orderData) {
        if (isset($orderData['data']) && !empty($orderData['data'])) {
            foreach ($orderData['data'] as &$order) {
                $orderGoodsData = (new SOrderRefundGoods())->getNormalOrderRefundGoodsList($order['order_refund_id'],'a.*,b.title,b.image,b.total_price,b.goods_num');
                $order['orderGoodsData'] = $orderGoodsData;
            }
        }
        return $orderData;
    }

    //修改售后订单
    public function saveRefundOrder(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        //参数校验
        $allParams = request()->param();
        $data = (new toCamelCase())->toCamelCaseArray($allParams,'1',2);
        try {
            $result = (new SOrderBus())->updateRefundById($data['order_refund_id'],$data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"修改订单",$result);
    }

    //修改售后订单不退款原因
    public function saveNotRefundOrder(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        //参数校验
        $allParams = request()->param();
        $data = (new toCamelCase())->toCamelCaseArray($allParams,'1',2);
        $data['status_time'] = date('Y-m-d H:i:s',time());
        $data['admin_id'] = $this->userId;
        $data['status'] = -1;
        Db::startTrans();
        try {
            $result = (new SOrderBus())->updateRefundById($data['order_refund_id'],$data);
            if($result){
                $saveOrderGoodsData = [
                    'is_refund' => 0,
                ];
                (new SOrderGoods())->saveOrderGoodsId($data['order_id'],$saveOrderGoodsData);
            }
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        Db::commit();
        return show(config("status.success"),"修改订单",$result);
    }

    /********************** 订单配置管理 *************************************/
    //查询订单配置
    public function getOrderConfigure(){
        $merId = $this->request->param("merId","","trim");
        try {
            $orderConfigureData = (new SOrderConfigure())->getOrderConfigure($merId);
            $orderConfigureData = (new toCamelCase())->toCamelCaseArray($orderConfigureData);
        }catch (\Exception $e){
            $orderConfigureData = [];
        }
        return show(config("status.success"),"订单配置",$orderConfigureData);
    }

    //修改订单配置
    public function saveOrderConfigure(){
        $allParams = request()->param();
        $data = (new toCamelCase)->toCamelCaseArray($allParams,1,2);
        // 初始化事务
        Db::startTrans();
        try {
            $result = (new SOrderConfigure())->updateById($data['order_configure_id'],$data);
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        Db::commit();
        return show(config("status.success"),"修改成功",$result);
    }
}
